package com.zhongshengnetwork.rightbe.game.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dd.CircularProgressButton;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.PublishSelectPicPopupWindow;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.game.model.PKAnswerModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKResultModel;
import com.zhongshengnetwork.rightbe.gsonmodel.PKResultUserInfo;
import com.zhongshengnetwork.rightbe.gsonmodel.PKUserModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EndPKActivity extends AppBaseActivity {

    private final static String url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.zhongshengnetwork.rightbe";//Constant.HOST+"downapp.do?";
    private final static String content = "王者对战，好玩又益智，赶紧来体验吧~";
    private List<String> list;
    private PublishSelectPicPopupWindow menuWindow;

    private PKUserModel pkUserModel;
    private PKAnswerModel pkAnswerModel;
    private PKUserModel roleUserModel;
    private PKUserModel anotherPKUserModel;
    private PKResultModel pkResultModel;
    private PKResultUserInfo acceptPKResultUserInfo;
    private PKResultUserInfo sendPKResultUserInfo;

    private CircularProgressButton endpk_right_window_bg;
    private CircularProgressButton endpk_left_window_bg;

    private CircularProgressButton pk_left_window_bg;
    private CircularProgressButton pk_left_window_circle;
    private ImageView pk_left_window_header;
    private TextView pk_left_window_nickname;

    private CircularProgressButton pk_right_window_bg;
    private CircularProgressButton pk_right_window_circle;
    private ImageView pk_right_window_header;
    private TextView pk_right_window_nickname;

    private ImageView pk_result_img;

    private CircularProgressButton pk_left_menu_1;
    private CircularProgressButton pk_left_menu_2;
    private CircularProgressButton pk_right_menu_1;
    private CircularProgressButton pk_right_menu_2;
    private TextView pk_add_gold;
    private TextView pk_add_playlevel;
    private CircularProgressButton pk_contiue_button;
    private CircularProgressButton pk_share_button;

    private MyIUiListener mIUiListener = new MyIUiListener();
    class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            Log.e("TAG","分享成功");
            getShareGold();
        }

        @Override
        public void onError(UiError uiError) {
            Log.e("TAG","分享出错");
        }

        @Override
        public void onCancel() {
            Log.e("TAG","分享取消");
        }

        @Override
        public void onWarning(int i) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
            }
        }
    }

    private void getShareGold(){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        String url = "miniapp/"+"pkappid"+"/usershare.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ToastUtil.show(CustomApplication.mContext,commonModel.getMsg());
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_end_pk);
        Intent intent = this.getIntent();
        pkUserModel = (PKUserModel) intent.getSerializableExtra("pkuser");
        roleUserModel = (PKUserModel) intent.getSerializableExtra("roleuser");
        anotherPKUserModel = (PKUserModel) intent.getSerializableExtra("anotherpkuser");
        pkAnswerModel = (PKAnswerModel) intent.getSerializableExtra("pkanswer");
        pkResultModel = (PKResultModel) intent.getSerializableExtra("pkresult");
        acceptPKResultUserInfo = (PKResultUserInfo) intent.getSerializableExtra("acceptpkresultuserinfo");
        sendPKResultUserInfo = (PKResultUserInfo) intent.getSerializableExtra("sendpkresultuserinfo");

        endpk_left_window_bg = (CircularProgressButton) findViewById(R.id.endpk_left_window_bg);
        endpk_left_window_bg.setBackgroundColor(getResources().getColor(R.color.limitBackgroundColor));
        endpk_left_window_bg.setStrokeColor(getResources().getColor(R.color.limitBackgroundColor));
        endpk_left_window_bg.setTextColor(Color.parseColor("#FFFFFF"));
        endpk_left_window_bg.setText(pkAnswerModel.getMyScore()+"分");

        endpk_right_window_bg = (CircularProgressButton) findViewById(R.id.endpk_right_window_bg);
        endpk_right_window_bg.setBackgroundColor(getResources().getColor(R.color.wordBgColor));
        endpk_right_window_bg.setStrokeColor(getResources().getColor(R.color.wordBgColor));
        endpk_right_window_bg.setTextColor(Color.parseColor("#FFFFFF"));
        endpk_right_window_bg.setText(pkAnswerModel.getAnotherScore()+"分");

        pk_left_window_bg = (CircularProgressButton) findViewById(R.id.pk_left_window_bg);
        pk_left_window_bg.setBackgroundColor(getResources().getColor(R.color.limitBackgroundColor));
        pk_left_window_bg.setStrokeColor(getResources().getColor(R.color.limitBackgroundColor));
        pk_left_window_circle = (CircularProgressButton) findViewById(R.id.pk_left_window_circle);
        pk_left_window_circle.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_left_window_circle.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_left_window_header = (ImageView) findViewById(R.id.pk_left_window_header);
        Glide.with(EndPKActivity.this).load(pkUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(EndPKActivity.this)).dontAnimate().into(pk_left_window_header);
        pk_left_window_nickname = (TextView) findViewById(R.id.pk_left_window_nickname);
        pk_left_window_nickname.setText(pkUserModel.getNickname());

        pk_right_window_bg = (CircularProgressButton) findViewById(R.id.pk_right_window_bg);
        pk_right_window_bg.setBackgroundColor(getResources().getColor(R.color.wordBgColor));
        pk_right_window_bg.setStrokeColor(getResources().getColor(R.color.wordBgColor));
        pk_right_window_circle = (CircularProgressButton) findViewById(R.id.pk_right_window_circle);
        pk_right_window_circle.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_right_window_circle.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_right_window_header = (ImageView) findViewById(R.id.pk_right_window_header);
        if (anotherPKUserModel != null){
            Glide.with(EndPKActivity.this).load(anotherPKUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(EndPKActivity.this)).dontAnimate().into(pk_right_window_header);
        }else {
            Glide.with(EndPKActivity.this).load(roleUserModel.getHeader()).skipMemoryCache(true).transform(new CircleTransform(EndPKActivity.this)).dontAnimate().into(pk_right_window_header);
        }
        pk_right_window_nickname = (TextView) findViewById(R.id.pk_right_window_nickname);
        if (anotherPKUserModel != null){
            pk_right_window_nickname.setText(anotherPKUserModel.getNickname());
        }else {
            pk_right_window_nickname.setText(roleUserModel.getNickname());
        }

        pk_result_img = (ImageView) findViewById(R.id.pk_result_img);
        if (pkAnswerModel.getMyScore() > 0 && pkAnswerModel.getMyScore() >= pkAnswerModel.getAnotherScore()){
            pk_result_img.setImageDrawable(getResources().getDrawable(R.drawable.pksuccess));
        }else {
            pk_result_img.setImageDrawable(getResources().getDrawable(R.drawable.pkfail));
        }

        pk_left_menu_1 = (CircularProgressButton)findViewById(R.id.pk_left_menu_1);
        pk_left_menu_1.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_left_menu_1.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_left_menu_2 = (CircularProgressButton)findViewById(R.id.pk_left_menu_2);
        pk_left_menu_2.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_left_menu_2.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_right_menu_1 = (CircularProgressButton)findViewById(R.id.pk_right_menu_1);
        pk_right_menu_1.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_right_menu_1.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_right_menu_2 = (CircularProgressButton)findViewById(R.id.pk_right_menu_2);
        pk_right_menu_2.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_right_menu_2.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_left_menu_1.setVisibility(View.INVISIBLE);
        pk_left_menu_2.setVisibility(View.INVISIBLE);
        pk_right_menu_1.setVisibility(View.INVISIBLE);
        pk_right_menu_2.setVisibility(View.INVISIBLE);
        int leftcount = 0;
        if (pkAnswerModel.getMyMaxLinkCorrectCount() > 1){
            leftcount=1;
            pk_left_menu_1.setText("连续答对"+pkAnswerModel.getMyMaxLinkCorrectCount()+"题");
            pk_left_menu_1.setVisibility(View.VISIBLE);
        }
        int rightcount = 0;
        if (pkAnswerModel.getAnohterMaxLinkCorrectCount() > 1){
            rightcount = 1;
            pk_right_menu_1.setText("连续答对"+pkAnswerModel.getAnohterMaxLinkCorrectCount()+"题");
            pk_right_menu_1.setVisibility(View.VISIBLE);
        }
        if (sendPKResultUserInfo.getWinLinkcount() > 1){
            if (sendPKResultUserInfo.getUserid().equals(CustomApplication.loginModel.getUid())){
                if (leftcount > 0){
                    pk_left_menu_2.setText("连续赢"+sendPKResultUserInfo.getWinLinkcount()+"局");
                    pk_left_menu_2.setVisibility(View.VISIBLE);
                }else {
                    pk_left_menu_1.setText("连续赢"+sendPKResultUserInfo.getWinLinkcount()+"局");
                    pk_left_menu_1.setVisibility(View.VISIBLE);
                }
            }else {
                if (rightcount > 0){
                    pk_right_menu_2.setText("连续赢"+sendPKResultUserInfo.getWinLinkcount()+"局");
                    pk_right_menu_2.setVisibility(View.VISIBLE);
                }else {
                    pk_right_menu_1.setText("连续赢"+sendPKResultUserInfo.getWinLinkcount()+"局");
                    pk_right_menu_1.setVisibility(View.VISIBLE);
                }
            }
        }

        if (acceptPKResultUserInfo.getWinLinkcount() > 1){
            if (acceptPKResultUserInfo.getUserid().equals(CustomApplication.loginModel.getUid())){
                if (leftcount > 0){
                    pk_left_menu_2.setText("连续赢"+acceptPKResultUserInfo.getWinLinkcount()+"局");
                    pk_left_menu_2.setVisibility(View.VISIBLE);
                }else {
                    pk_left_menu_1.setText("连续赢"+acceptPKResultUserInfo.getWinLinkcount()+"局");
                    pk_left_menu_1.setVisibility(View.VISIBLE);
                }
            }else {
                if (rightcount > 0){
                    pk_right_menu_2.setText("连续赢"+acceptPKResultUserInfo.getWinLinkcount()+"局");
                    pk_right_menu_2.setVisibility(View.VISIBLE);
                }else {
                    pk_right_menu_1.setText("连续赢"+acceptPKResultUserInfo.getWinLinkcount()+"局");
                    pk_right_menu_1.setVisibility(View.VISIBLE);
                }
            }
        }

        pk_add_gold = (TextView) findViewById(R.id.pk_add_gold);
        pk_add_playlevel = (TextView) findViewById(R.id.pk_add_playlevel);
        if (acceptPKResultUserInfo.getUserid().equals(CustomApplication.loginModel.getUid())){
            pk_add_gold.setText("金币：+"+pkResultModel.getAddgoldcountaccept());
            pk_add_playlevel.setText("Lv.：+"+pkResultModel.getAddplaylevelaccept());
        }else if (sendPKResultUserInfo.getUserid().equals(CustomApplication.loginModel.getUid())){
            pk_add_gold.setText("金币：+"+pkResultModel.getAddgoldcountsend());
            pk_add_playlevel.setText("Lv.：+"+pkResultModel.getAddplaylevelsend());
        }

        pk_contiue_button = (CircularProgressButton) findViewById(R.id.pk_contiue_button);
        pk_contiue_button.setBackgroundColor(getResources().getColor(R.color.mainColor));
        pk_contiue_button.setStrokeColor(getResources().getColor(R.color.mainColor));
        pk_contiue_button.setText("继续挑战");

        pk_share_button = (CircularProgressButton) findViewById(R.id.pk_share_button);
        pk_share_button.setBackgroundColor(getResources().getColor(R.color.limitBackgroundColor));
        pk_share_button.setStrokeColor(getResources().getColor(R.color.limitBackgroundColor));
        if (pkAnswerModel.getMyScore() > 0 && pkAnswerModel.getMyScore() >= pkAnswerModel.getAnotherScore()){
            pk_share_button.setText("分享炫耀");
        }else {
            pk_share_button.setText("分享好玩");
        }

        list = new ArrayList<String>();
        list.add("分享给微信好友");
        list.add("分享到微信朋友圈");
        list.add("分享给QQ好友");
        list.add("分享到QQ空间");
        //list.add("取消");
        registerBoradcastReceiver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    public void onClickBack(View view){
        finish();
    }

    public void onClickContiue(View view){
//        Intent intent = new Intent(EndPKActivity.this, PKMenuActivity.class);
//        startActivity(intent);
        finish();
    }

    public void onClickShare(View view){
        share(view);
    }

    private void share(View v){
        /*
        menuWindow = new PublishSelectPicPopupWindow(EndPKActivity.this,itemsOnClick,list);
        // 显示窗口
        menuWindow.showAtLocation(v,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        */
        String title = "";
        if (pkAnswerModel.getMyScore() > 0 && pkAnswerModel.getMyScore() == pkAnswerModel.getAnotherScore()){
            title = "我在王者对战中大获全胜，不服来战~";
        }else if (pkAnswerModel.getMyScore() > pkAnswerModel.getAnotherScore()){
            title = "我在王者对战中大获全胜，不服来战~";
        }else{
            title = "我在王者对战中不敌对手，诚邀老铁来助阵！";
        }
        final String t = title;
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(EndPKActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : list){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which == 1){
                        //分享给微信好友
                        String des = content;
                        shareToWX(1,url,t,des);
                    }else if (which == 2){
                        //分享到朋友圈
                        shareToWX(0,url,t,content);
                    }else if (which == 3){
                        //分享到qq
                        shareToQQ(0,url,t,content);
                    }else if (which == 4){
                        //qq空间
                        shareToQQ(1,url,t,content);
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    //分享到qq
    private Bundle params;
    private void shareToQQ(int type, String url,String title,String content){
        params = new Bundle();
        if (type == 0){//分享给QQ好友
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,url);// 内容地址
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,"http://image.daydayrise.net/360@2x.png");// 网络图片地址
            params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "");//其它附加功能
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQQ(EndPKActivity.this, params, mIUiListener);
                }
            });
        }else {
            //分享到QQ空间
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE,QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);// 标题
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, content);// 摘要
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url);// 内容地址
            ArrayList<String> imgUrlList = new ArrayList<>();
            imgUrlList.add("http://image.daydayrise.net/360@2x.png");
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imgUrlList);// 图片地址
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CustomApplication.mTencent.shareToQzone(EndPKActivity.this, params, mIUiListener);
                }
            });
        }

    }

    // 为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            String title = "";
            if (pkAnswerModel.getMyScore() > 0 && pkAnswerModel.getMyScore() == pkAnswerModel.getAnotherScore()){
                title = "我在王者对战中大获全胜，不服来战~";
            }else if (pkAnswerModel.getMyScore() > pkAnswerModel.getAnotherScore()){
                title = "我在王者对战中大获全胜，不服来战~";
            }else{
                title = "我在王者对战中不敌对手，诚邀老铁来助阵！";
            }
            switch (v.getId()) {
                case R.id.first_button://分享给微信好友
                    String des = content;
                    shareToWX(1,url,title,des);
                    break;
                case R.id.second_button://分享到微信朋友圈
                    shareToWX(0,url,title,content);
                    break;
                case R.id.third_button:
                    break;
                default:
                    break;
            }

        }
    };

    //分享到微信
    private void shareToWX(int type,String url,String title,String content){
        //初始化一个WXWebpageObject对象，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        //用WXWebpageObject对象初始化一个WXMediaMessage对象，填写标题、描述
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = content;
        Bitmap thumb = BitmapFactory.decodeResource(getResources(),R.mipmap.icon);
        msg.thumbData = CommonUtils.bitmapToByteArray(thumb,true);
        //构成一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message = msg;
        req.scene = type==0 ? SendMessageToWX.Req.WXSceneTimeline:SendMessageToWX.Req.WXSceneSession;
        CustomApplication.mWxApi.sendReq(req);

    }

    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.WX_Share_Result)) {
                //微信分享成功
                getShareGold();
            }
        }
    };

    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        //添加接收广播类型
        myIntentFilter.addAction(BroadcastDefine.WX_Share_Result);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
}
